// 记忆函数
// const _ = require('lodash');

function getArea(r) {
    console.log(r);
    return Math.PI * r * r;
}

// let getAreaWithMemory = _.memoize(getArea);
// console.log(getAreaWithMemory(4));
// console.log(getAreaWithMemory(4));
// console.log(getAreaWithMemory(4));

// 模拟 memoize 方法的实现
function memoize(fn) {
    let cache = {};
    return function () {
        const key = JSON.stringify(arguments);
        let result = cache[key];
        if (result) {
            return result;
        }
        result = fn.apply(fn, arguments);
        cache[key] = result;
        return result;
    };
}

let getAreaWithMemory = memoize(getArea);
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(4));
console.log(getAreaWithMemory(5));
console.log(getAreaWithMemory(5));
